package aes.client;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;
import common.*;

public class ExamExecutionManagerUI extends JPanel implements ActionListener, Observer{

	private static final long serialVersionUID = -1196955858992799327L;

	private ClientUI ui;
	private Client c;
	private JButton btnLock;
	private JButton btnAddTime;
	private JButton btnBack;
	private JTextField textCode;
	private JTextField textNotes;
	private JTextField textAddTime;
    private JButton btnApproveExams;
	
    /**
	 * Constructor
	 * @param c Client object reference
	 * @param ui ClientUI object reference
	 */
    public ExamExecutionManagerUI(Client c,ClientUI ui) {
		super();
		this.ui = ui;
		this.c = c;

		JFrame frame = new JFrame();
		frame.setSize(640, 480);
		frame.getContentPane().add(this);

		c.addObserver(this);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{610};
		setLayout(gridBagLayout);


		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
		panel.setPreferredSize(new Dimension(600,400));

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(5, 0, 5, 0);
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel,gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 21};
		gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0};
		panel.setLayout(gbl_panel);

		JLabel lblExamExecTeacherTitle = new JLabel("Exam Execution Manager");
		lblExamExecTeacherTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblExamExecTeacherTitle.setVerticalAlignment(SwingConstants.TOP);
		lblExamExecTeacherTitle.setBounds(7, 10, 70, 17);
		lblExamExecTeacherTitle.setFont(new Font("Tahoma", Font.BOLD, 14));

		GridBagConstraints gbc_lblExamExecTeacherTitle = new GridBagConstraints();
		gbc_lblExamExecTeacherTitle.anchor = GridBagConstraints.NORTH;
		gbc_lblExamExecTeacherTitle.gridwidth = 2;
		gbc_lblExamExecTeacherTitle.fill = GridBagConstraints.BOTH;
		gbc_lblExamExecTeacherTitle.insets = new Insets(5, 0, 5, 0);
		gbc_lblExamExecTeacherTitle.gridx = 0;
		gbc_lblExamExecTeacherTitle.gridy = 0;
		panel.add(lblExamExecTeacherTitle, gbc_lblExamExecTeacherTitle);

		JLabel lblCode = new JLabel("Code:");
		lblCode.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblCode = new GridBagConstraints();
		gbc_lblCode.anchor = GridBagConstraints.EAST;
		gbc_lblCode.insets = new Insets(0, 10, 5, 5);
		gbc_lblCode.gridx = 0;
		gbc_lblCode.gridy = 2;
		panel.add(lblCode, gbc_lblCode);

		textCode = new JTextField();
		GridBagConstraints gbc_textCode = new GridBagConstraints();
		gbc_textCode.insets = new Insets(0, 0, 5, 10);
		gbc_textCode.fill = GridBagConstraints.HORIZONTAL;
		gbc_textCode.gridx = 1;
		gbc_textCode.gridy = 2;
		panel.add(textCode, gbc_textCode);
		MaxLengthTextDocument maxLength = new MaxLengthTextDocument();
		maxLength.setMaxChars(5);
		textCode.setDocument(maxLength);

		JLabel lblAddTime = new JLabel("Additional Time:");
		lblCode.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblAddTime = new GridBagConstraints();
		gbc_lblAddTime.anchor = GridBagConstraints.EAST;
		gbc_lblAddTime.insets = new Insets(0, 10, 5, 5);
		gbc_lblAddTime.gridx = 0;
		gbc_lblAddTime.gridy = 3;
		panel.add(lblAddTime, gbc_lblAddTime);

		textNotes = new JTextField();
		GridBagConstraints gbc_textNotes = new GridBagConstraints();
		gbc_textNotes.insets = new Insets(0, 0, 5, 10);
		gbc_textNotes.fill = GridBagConstraints.HORIZONTAL;
		gbc_textNotes.gridx = 1;
		gbc_textNotes.gridy = 4;
		panel.add(textNotes, gbc_textNotes);
		maxLength.setMaxChars(5);

		JLabel lblAddNotes = new JLabel("Notes:");
		lblCode.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblAddNotes = new GridBagConstraints();
		gbc_lblAddNotes.anchor = GridBagConstraints.EAST;
		gbc_lblAddNotes.insets = new Insets(0, 10, 5, 5);
		gbc_lblAddNotes.gridx = 0;
		gbc_lblAddNotes.gridy = 4;
		panel.add(lblAddNotes, gbc_lblAddNotes);

		textAddTime = new JTextField();
		GridBagConstraints gbc_textAddTime = new GridBagConstraints();
		gbc_textAddTime.insets = new Insets(0, 0, 5, 10);
		gbc_textAddTime.fill = GridBagConstraints.HORIZONTAL;
		gbc_textAddTime.gridx = 1;
		gbc_textAddTime.gridy = 3;
		panel.add(textAddTime, gbc_textAddTime);
		maxLength.setMaxChars(5);

		btnLock = new JButton("Lock Exam");
		btnLock.setIcon(new ImageIcon(ExamExecutionManagerUI.class.getResource("/aes/client/images/lock.png")));
		btnLock.addActionListener(this); 
		btnAddTime = new JButton("ADD Time", new ImageIcon(ExamExecutionManagerUI.class.getResource("/aes/client/images/accept.png")));
		btnAddTime.addActionListener(this); 
		GridBagConstraints gbc_btnAddTime = new GridBagConstraints();
		gbc_btnAddTime.insets = new Insets(5, 0, 5, 10);
		gbc_btnAddTime.anchor=GridBagConstraints.WEST;
		gbc_btnAddTime.gridx = 1;
		gbc_btnAddTime.gridy = 5;
		panel.add(btnAddTime, gbc_btnAddTime);
		btnAddTime.setBounds(353, 7, 57, 23);
		

		GridBagConstraints gbc_btnLock = new GridBagConstraints();
		gbc_btnLock.insets = new Insets(5, 5, 5, 10);
		gbc_btnLock.anchor=GridBagConstraints.CENTER;
		gbc_btnLock.gridx = 1;
		gbc_btnLock.gridy = 5;
		panel.add(btnLock, gbc_btnLock);
		btnLock.setBounds(353, 7, 57, 23);
		
		btnApproveExams = new JButton("Exam Checking");
		btnApproveExams.addActionListener(this);
		btnApproveExams.setIcon(new ImageIcon(ExamExecutionManagerUI.class.getResource("/aes/client/images/Report.png")));
		GridBagConstraints gbc_btnApproveExams = new GridBagConstraints();
		gbc_btnApproveExams.anchor=GridBagConstraints.EAST;
		gbc_btnApproveExams.insets = new Insets(5, 0, 5, 10);
		gbc_btnApproveExams.gridx = 1;
		gbc_btnApproveExams.gridy = 5;
		panel.add(btnApproveExams, gbc_btnApproveExams);

		JPanel panel_2 = new JPanel();
		GridBagConstraints gbc_panel_2 = new GridBagConstraints();
		gbc_panel_2.anchor = GridBagConstraints.SOUTH;
		gbc_panel_2.insets = new Insets(30, 0, 0, 0);
		gbc_panel_2.fill = GridBagConstraints.HORIZONTAL;
		gbc_panel_2.gridx = 0;
		gbc_panel_2.gridy = 8;
		gbc_panel_2.gridwidth = 2;
		panel.add(panel_2, gbc_panel_2);
		panel_2.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

		btnBack = new JButton("Back", new ImageIcon(ExamsManagerUI.class.getResource("/aes/client/images/back.png")));
		btnBack.addActionListener(this); 
		GridBagConstraints gbc_btnBack = new GridBagConstraints();
		gbc_btnBack.insets = new Insets(5, 5, 5, 5);
		panel_2.add(btnBack, gbc_btnBack);
		btnBack.setBounds(353, 7, 57, 23);

	}



	/**
	 * 
	 */


	@SuppressWarnings("static-access")
	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.REQUEST_ADDITIONAL_TIME)) {
				boolean res = Boolean.parseBoolean(ms.getParams()[1].toString());
				if (res == false) {

					ui.ShowMessageBox("ERROR", "Can't request additional time", JOptionPane.ERROR_MESSAGE);
				}
				else {

					ui.ShowMessageBox("Information", "Additional time was requested: " , JOptionPane.INFORMATION_MESSAGE);
					textCode.setText("");
					textNotes.setText("");
					textAddTime.setText("");
				}

			}

			else if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.LOCK_EXAM_EXECUTION)) {
				boolean res = Boolean.parseBoolean(ms.getParams()[1].toString());
				if (res == false) {

					ui.ShowMessageBox("ERROR", "Can't lock exam", JOptionPane.ERROR_MESSAGE);
				}
				else {

					ui.ShowMessageBox("Information", "Exam locks succeed", JOptionPane.INFORMATION_MESSAGE);
					textCode.setText("");
					textNotes.setText("");
					textAddTime.setText("");
				}

			}
			
			 if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_STATUS_OF_EXAM_EXECUTION)) {
				int res = Integer.parseInt(ms.getParams()[1].toString());
				
				if(res == 4){
					ui.SetContent(ui.GRADE_APPROVAL_SCREEN);
					ExamCheckingUI panel= ((ExamCheckingUI)ui.getContentPane());
					panel.setExamExecutionCode(textCode.getText().toString());
					panel.loadExams();
				} 
				else{
					ui.ShowMessageBox("ERROR", "Can't approve exams with code " + textCode.getText().toString(), JOptionPane.ERROR_MESSAGE);
				}
			}
		}

	}

	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(btnBack)) {
			ui.SetContent(ui.TEACHER_EXAM_EXECUTION_SCREEN);
		}if (e.getSource().equals(btnApproveExams)) {
			if (checkForm1())
			{

				
			CommandMessage msg = new CommandMessage(CommandMessage.GET_STATUS_OF_EXAM_EXECUTION, new Object[] {(String)(textCode.getText().toString()), ui.getUser().getId()});
			try {
				c.sendToServer(msg);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
		else if (e.getSource().equals(btnAddTime)) {
			if (checkForm())
			{

				CommandMessage msg = new CommandMessage(CommandMessage.REQUEST_ADDITIONAL_TIME, new Object[] {(String)(textCode.getText().toString()),Integer.parseInt(textAddTime.getText().toString()),(String)(textNotes.getText().toString()), ui.getUser().getId()});
				try {
					c.sendToServer(msg);
				} catch (IOException ex) {
					ex.printStackTrace();
				}

			}
		}

		else if (e.getSource().equals(btnLock)) {
			if (checkForm1())
			{
				// Check if code is correct and lock exam.
				CommandMessage msg = new CommandMessage(CommandMessage.LOCK_EXAM_EXECUTION, new Object[] {(String)(textCode.getText().toString()), ui.getUser().getId()});
				try {
					c.sendToServer(msg);
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}
	/**
	 * 	Check correctness of form to add time to exam execution
	 * @return true - right form ,false -wrong form
	 */
	@SuppressWarnings("static-access")
	private boolean checkForm() {
		int addTime;

		if (textCode.getText().trim().length() != 4) {
			ui.ShowMessageBox("ERROR", "Please fill execution code 4 characters long", JOptionPane.ERROR_MESSAGE);
			return false; 
		}
		try {  
			addTime=Integer.parseInt( textAddTime.getText() );  
			if (addTime < 1)
			{
				ui.ShowMessageBox("ERROR", "Additional time must be positive", JOptionPane.ERROR_MESSAGE);
				return false; 
			}
		}  
		catch( Exception ex) {  
			ui.ShowMessageBox("ERROR", "Solve time must be numeric", JOptionPane.ERROR_MESSAGE);
			return false;  
		}

		return true;
	}
	/**
	 * Check form to lock
	 * @return
	 */
	@SuppressWarnings("static-access")
	private boolean checkForm1() {	
		if (textCode.getText().trim().length() != 4) {
			ui.ShowMessageBox("ERROR", "Please fill execution code 4 characters long", JOptionPane.ERROR_MESSAGE);
			return false; 
		}
		return true;
	}




}
